package development;

import java.util.Vector;

import state.Clip;
import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.component.BottomBar;
import state.component.Event;
import state.component.EventListener;
import state.component.GameMenu;
import state.component.GameScrollBar;
import state.component.MultiTab;
import state.component.TextField;
import state.font.FontManager;
import state.font.ImageText;
import state.util.GameColor;
import state.util.GameStringUtils;
import state.util.Hashtable;
import state.util.ImageUtil;
import state.util.NumberUtil;
import state.util.array.StringArray;
import development.app.mxh.FrmAccount;
import development.bean.UserBean;
import development.group.FrmGroupFriendAndTop;
import development.group.FrmGroupListTableFreeUserChat;
import development.group.FrmGroupMenu;
import development.group.FrmGroupTableFreeUserFriend;
import development.socket.SocketClientUtil;

public class FrmFriend extends GameForm implements EventListener {
  private final int DISTANCE = 21;
  private final int DX = 10;
  private final int DY = 48;

  private GameImage onlineImage;
  private GameImage offlineImage;
  private GameImage popupImage;

  private ImageText text8;
  private int chooseIndex;

  public boolean isReceivedFriendList = false;

  private GameScrollBar scrollBar;
  private Clip textView; // Là khung nhìn để vẽ đoạn text ra

  private int textY;

  private String account;

  private TextField txtTransferMoney;

  private final int DEFAULT_TEXT_X = 5;

  private boolean isShowTransferMoney;

  private GameMenu menu;

  private static GameForm singleton;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmFriend();
    }
    return singleton;
  }

  public void init(Hashtable parameters) {
    if (parameters != null) {
      account = (String) parameters.get("User");
      account = GameStringUtils.nvl(account, Global.currentUser.getName());
    } else {
      account = Global.currentUser.getName();
    }

    isReceivedFriendList = false;
    chooseIndex = 0;
    SocketClientUtil.requestFriendList(account);
    popupImage = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "bg_popup.png");

    onlineImage = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "icon_online.png");
    offlineImage = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "icon_Nghi-ngoi.png");

    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    textY = DY;
    textView = new Clip(DX, DY - 13, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT - DY - 30); // Là khung nhìn để vẽ đoạn text ra
    scrollBar = new GameScrollBar(Constants.SCREEN_WIDTH - 5, 25, 5, Constants.SCREEN_HEIGHT - 50, textView, _manager);

    txtTransferMoney = new TextField(_manager, TextField.CONSTRAINT_NUMERIC, null);
    txtTransferMoney.setSize(GameConstants.SCREEN_WIDTH - DEFAULT_TEXT_X * 2, text8.getHeight());
    txtTransferMoney.setAnchor(GameConstants.BOTTOM_LEFT_ANCHOR);
    txtTransferMoney.setPosition(DEFAULT_TEXT_X, GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight() - 5);
    txtTransferMoney.setVisible(false);

    isShowTransferMoney = false;
    _manager.enableTouchPad();
  }

  private void createMenu() {
    // Create bottom bar
    menu = new GameMenu(null, new String[] { "Về menu chính", "Update danh sách", "Mời chơi", "Hủy kết bạn", "Xem tài khoản", "Chuyển tiền" }, 6, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);
    BottomBar bottomBar = DrawUtils.getBottomBar(FrmGroupTableFreeUserFriend.instance().getManager());
    bottomBar.setLabels("Menu", "Mời chơi", "Trở về");
    bottomBar.setLeftMenu("Menu", menu);
  }

  public void draw(Graphics g) {
    DrawUtils.drawBackground(g);

    if (!isReceivedFriendList) {
      g.drawImage(popupImage, GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT / 2, GameConstants.CENTER_ANCHOR);
      text8.drawString2(g, "Đang cập nhật danh sách", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT / 2, GameConstants.CENTER_ANCHOR);
    } else {
      Clip.setClip(g, textView);
      for (int i = 0; i < Global.friends.size(); i++) {
        g.setColor(GameColor.WHITE_CODE);
        g.drawLine(DX, textY - DISTANCE / 2 + i * DISTANCE, GameConstants.SCREEN_WIDTH - DX, textY - DISTANCE / 2 + i * DISTANCE);

        UserBean friend = (UserBean) Global.friends.elementAt(i);
        int color = GameColor.WHITE_CODE;
        if (i == chooseIndex) {
          g.setColor(0x662221);
          g.fillRect(DX, textY - DISTANCE / 2 + i * DISTANCE + 2, GameConstants.SCREEN_WIDTH - 2 * DX, DISTANCE - 3);
          color = GameColor.YELLOW_CODE;
        }

        if (friend.isOnline()) {
          g.drawImage(onlineImage, 15, textY + i * DISTANCE, GameConstants.CENTER_ANCHOR);
        } else {
          g.drawImage(offlineImage, 15, textY + i * DISTANCE, GameConstants.CENTER_ANCHOR);
        }
        text8.drawString3(g, friend.getUsername(), color, 26, textY + i * DISTANCE, GameConstants.VCENTER_LEFT_ANCHOR, scrollBar);
        text8.drawString3(g, friend.getLocationInfo(), color, GameConstants.SCREEN_WIDTH / 2 - 10, textY + i * DISTANCE, GameConstants.VCENTER_LEFT_ANCHOR, scrollBar);
      }
      g.setClip(0, 0, Constants.SCREEN_WIDTH, Constants.SCREEN_HEIGHT);
      scrollBar.draw(g);
    }
    if (isShowTransferMoney) {
      drawTransferMoney(g);
      DrawUtils.getBottomBar(FrmGroupTableFreeUserFriend.instance().getManager()).setLabels("Đóng", "Chuyển", "Xóa");
    } else {
      DrawUtils.getBottomBar(FrmGroupTableFreeUserFriend.instance().getManager()).setLeftMenu("Menu", menu);
      DrawUtils.getBottomBar(FrmGroupTableFreeUserFriend.instance().getManager()).setCenterLabel("Mời chơi");
      DrawUtils.getBottomBar(FrmGroupTableFreeUserFriend.instance().getManager()).setRightLabel("Trở về");
    }
  }

  private void drawTransferMoney(Graphics g) {
    g.setColor(0xA9A9A9);
    g.fillRect(0, GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight() - 40, GameConstants.SCREEN_WIDTH, GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight() - 40);
    g.drawRect(0, GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight() - 40, GameConstants.SCREEN_WIDTH, GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight() - 40);
    text8.drawString2(g, "Số tiền muốn chuyển:", GameColor.WHITE_CODE, 5, GameConstants.SCREEN_HEIGHT - DrawUtils.getBottomBarHeight() - 25, GameConstants.BOTTOM_LEFT_ANCHOR);
    txtTransferMoney.draw(g);
  }

  public void onActionPerform(Event event) {
    if (MultiTab.OPEN_TAB_EVENT.equals(event.getAction())) {
      createMenu();
      return;
    }

    // "Cập nhật danh sách", "Mời chơi", "Hủy kết bạn"
    String action = event.getAction();
    if (action.equals("Về menu chính")) {
      Global.nextState(FrmGroupMenu.instance(), null);
    } else if (action.equals("Update danh sách")) {
      SocketClientUtil.requestFriendList(account);
    } else if (action.equals("Mời chơi")) {
      if (Global.friends.size() == 0) {
        Global.alert.showAlert(this, GameAlert.OK_TYPE, "Không có người bạn nào");
        return;
      }

      UserBean friend = (UserBean) Global.friends.elementAt(chooseIndex);
      if (friend.isOnline()) {
        Vector choosedUsers = new Vector();
        choosedUsers.addElement(friend.getUsername());
        SocketClientUtil.invitePlay(choosedUsers, Global.currentGame.getId());
      } else {
        Global.alert.showAlert3(this, GameAlert.OK_TYPE, StringArray.create1( "Người chơi đang", "không online" ));
      }
    } else if (action.equals("Hủy kết bạn")) {
      if (!Global.currentUser.getName().equals(account)) {
        return;
      }
      if (Global.friends.size() == 0) {
        Global.alert.showAlert(this, GameAlert.OK_TYPE, "Không có người bạn nào");
        return;
      }
      SocketClientUtil.removeFriendRequest(((UserBean) Global.friends.elementAt(chooseIndex)).getUsername());
    } else if (action.equals("Xem tài khoản")) {
      UserBean friend = (UserBean) Global.friends.elementAt(chooseIndex);
      Hashtable parameters = new Hashtable();
      parameters.put("User", friend.getUsername());
      FrmAccount.backForm = parentGroup;
      Global.nextState(FrmAccount.instance(), parameters);
    } else if (action.equals("Chuyển tiền")) {
      isShowTransferMoney = true;
      txtTransferMoney.setVisible(true);
      txtTransferMoney.setFocused(true);
    }
  }

  public void keyReleased(int keyCode) {
    switch (keyCode) {
    case Key.SOFT_LEFT:
      if (isShowTransferMoney) {
        txtTransferMoney.clearText();
        txtTransferMoney.setVisible(false);
        isShowTransferMoney = false;
      }
      break;
    case Key.SOFT_RIGHT:
      if (isShowTransferMoney && txtTransferMoney.isFocused()) {
        txtTransferMoney.deleteLastChar();
        return;
      }
      if (parentGroup instanceof FrmGroupTableFreeUserFriend) {
        account = null;
        Global.nextState(FrmGroupListTableFreeUserChat.instance(), null);
      } else if (parentGroup instanceof FrmGroupFriendAndTop) {
        account = null;
        if (FrmGroupFriendAndTop.backForm != null) {
          Global.nextState(FrmGroupFriendAndTop.backForm, FrmGroupFriendAndTop.parameters);
        } else {
          if (Global.systemCanvas.lastState instanceof FrmDownloadResource) {
            GameGlobal.nextState(FrmGroupMenu.instance(), null);
          } else {
            GameGlobal.nextState(Global.systemCanvas.lastState, FrmGroupFriendAndTop.parameters);
          }
        }
      }
      break;
    case Key.UP:
    case Key.K_2:
      if (chooseIndex > 0) {
        chooseIndex--;
        if (textY + chooseIndex * DISTANCE < DY) {
          textY += DISTANCE;
        }
      }
      break;
    case Key.DOWN:
    case Key.K_8:
      if (chooseIndex < Global.friends.size() - 1) {
        chooseIndex++;
        if (textY + chooseIndex * DISTANCE > Constants.SCREEN_HEIGHT / 2) {
          textY -= DISTANCE;
        }
      }
      break;
    case Key.FIRE:
    case Key.K_5:
      if (isShowTransferMoney && txtTransferMoney.isFocused() && txtTransferMoney.getText().length() == 0) {
        txtTransferMoney.pointerReleased(txtTransferMoney, txtTransferMoney.getRealX(), txtTransferMoney.getRealY());
        return;
      }
      if (isShowTransferMoney) {
        int money = 0;
        String strMoney = txtTransferMoney.getText();
        if (strMoney == null || strMoney.equals("")) {
          Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bạn chưa nhập số $");
          return;
        }
        
        money = NumberUtil.parseInt(strMoney);
        if (money == NumberUtil.ERROR_VALUE) {
          Global.alert.showAlert(this, GameAlert.OK_TYPE, "Số $ phải là kiểu số");
          return;
        }
        String friend = ((UserBean) Global.friends.elementAt(chooseIndex)).getUsername();
        SocketClientUtil.transferMoney(Global.currentUser.getName(), friend, money);
        return;
      }
      onActionPerform(new Event(null, "Mời chơi"));
      break;
    default:
      if (txtTransferMoney.isFocused()) {
        txtTransferMoney.keyReleased(null, keyCode);
      }
    }
  }

  public void destroy() {
    popupImage = null;
    text8 = null;
    onlineImage = null;
    offlineImage = null;
    account = null;
    txtTransferMoney = null;
    isShowTransferMoney = false;
    menu = null;
  }
}
